import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import * as NoteAPI from '@/api/notes'
import type { Note, Page, Result } from '../types'

export const useNoteStore = defineStore('note', () => {
  const notes = ref<Note[]>([])

  // 分页请求
  const getNotes = (payload: Page) => {
    NoteAPI.getNotesList<Result<Note[]>>(payload.page, payload.size).then((res) => {
      if (payload.page === 1) {
        notes.value = [...res.data]
      } else {
        notes.value.push(...res.data)
      }
    })
  }

  // 搜索
  const searchNotes = (payload: string) => {
    NoteAPI.getNoteListByContent<Result<Note[]>>(payload).then((res) => {
      notes.value = [...res.data]
      // notes.value.push(...res.data)
    })
  }
  // 添加
  const addNote = (payload: Note) => {
    NoteAPI.addNote<Result<Note>>(payload).then((res) => {
      notes.value.push(res.data)
    })
  }
  // 修改
  const updateNote = (payload: any) => {
    NoteAPI.updateNote(payload.id, payload.note).then(() => {
      notes.value.forEach((note: Note) => {
        if (note._id === payload.id) {
          note.content = payload.note.content
          note.dates = payload.note.dates
        }
      })
    })
  }
  // 删除
  const deleteNote = (payload: string) => {
    NoteAPI.deleteNote(payload).then(() => {
      const index = notes.value.findIndex((note: Note) => {
        return note._id === payload
      })
      notes.value.splice(index, 1)
    })
  }
  return { notes, getNotes, searchNotes, addNote, updateNote, deleteNote }
})
